package com.xysoft.framework.mvc;

import java.util.Locale;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

public class CombinedViewResolver implements ViewResolver {
	
	private ViewResolver freemarkerViewResolver;
	
	private ViewResolver jacksonViewResolver;
	
	private ViewResolver defaultViewResolver;
	
	public void setFreemarkerViewResolver(ViewResolver freemarkerViewResolver) {
		this.freemarkerViewResolver = freemarkerViewResolver;
	}

	public void setJacksonViewResolver(ViewResolver jacksonViewResolver) {
		this.jacksonViewResolver = jacksonViewResolver;
	}

	public void setDefaultViewResolver(ViewResolver defaultViewResolver) {
		this.defaultViewResolver = defaultViewResolver;
	}

	@Override
	public View resolveViewName(String viewName, Locale locale) throws Exception {
		if(StringUtils.startsWithAny(viewName, ViewConstants.FORWARD_VIEW_PREFIX, ViewConstants.REDIRECT_VIEW_PREFIX)) {
			return freemarkerViewResolver.resolveViewName(viewName, locale);
		}
		
		if(StringUtils.startsWith(viewName, ViewConstants.FREEMARKER_VIEW_PREFIX)) {
			return freemarkerViewResolver.resolveViewName(StringUtils.removeStart(viewName, ViewConstants.FREEMARKER_VIEW_PREFIX), locale);
		}
		
		if(StringUtils.startsWith(viewName, ViewConstants.JSON_VIEW_PREFIX)) {
			return jacksonViewResolver.resolveViewName(viewName, locale);
		}
		
		return defaultViewResolver.resolveViewName(viewName, locale);
	}
	
}
